package com.huluobo.a2206parkdemo.sign

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2206parkdemo.R
import com.huluobo.a2206parkdemo.databinding.ActivitySignBinding
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class SignActivity : BaseActivity<ActivitySignBinding, SignViewModel>() {
    override fun initData() {
        vm.signStartSuccess.observe(this) {
            ToastUtils.showLong("签到成功")
            binding.signBtn.text = "签退"
            SPUtils.getInstance().put(Const.PARAM_IS_SIGN, true)
        }

        vm.signEndSuccess.observe(this) {
            ToastUtils.showLong("签退成功")
            binding.signBtn.text = "签到"
            SPUtils.getInstance().put(Const.PARAM_IS_SIGN, false)
        }
    }

    override fun initView() {
        binding.signHeader.headerBack.setOnClickListener { finish() }
        binding.signHeader.headerTitle.text = "签到/签退"

        if (SPUtils.getInstance().getBoolean(Const.PARAM_IS_SIGN)) {
            binding.signBtn.text = "签退"
        } else {
            binding.signBtn.text = "签到"
        }

        binding.signBtn.setOnClickListener {
            if (SPUtils.getInstance().getBoolean(Const.PARAM_IS_SIGN)) {
                //签退接口
                val map = mutableMapOf<String, Any>()
                map[Const.PARAM_END_TIME] = System.currentTimeMillis() / 1000
                map[Const.PARAM_END_ADDRESS] = "天津市"
                map[Const.PARAM_USER_ID] = SPUtils.getInstance().getInt(Const.PARAM_UID)

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                vm.signEnd(body)
            } else {
                //签到接口
                val map = mutableMapOf<String, Any>()
                map[Const.PARAM_START_TIME] = System.currentTimeMillis() / 1000
                map[Const.PARAM_START_ADDRESS] = "天津市"
                map[Const.PARAM_USER_ID] = SPUtils.getInstance().getInt(Const.PARAM_UID)

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                vm.signStart(body)
            }
        }
    }
}